/*
 * Copyright (c) 2011 Junichiro Okuno
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Junichiro Okuno.
 */

/**
 * EchoClientOneLine - create client socket, send one line,
 * read it back. See also EchoClient.java, slightly fancier.
 * @author J. Okuno
 * Reference: Darwin. I F (2002). Java Cookbook, O'Reilly
*/

package tcp_net;

import tcp_net.debug.DebugInfo;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import java.net.*;

public abstract class Client {
	
	/**
		Debug information
	*/
	private final static boolean DEBUG = DebugInfo.CLIENT_DEBUG;
	
	/**
		Hostname or IP address
	*/
	protected String hostName;
	
	/**
		Port number
	*/
	protected int port;
	
	/**
		Network socket for the client
	*/
	private Socket sock;
	
	/**
		An I/O reader for the client 
	*/
	private BufferedReader is;
	
	/**
		An I/O write for  the client
	*/
	private PrintWriter os;
	
	/**
		Init the client object
		@param hm a hostname for the connecting server
		@param pt a port number for the connecting server
	*/
	public Client(String hm, int pt)
	{
		hostName = hm;
		port = pt;
		
		DebugInfo.print(DEBUG, "Client created. Host name: "+hostName+" Port: "+port);
	}

	/**
		This method connects to the server
	*/
	public void connect()
	{
		try 
		{ 
			sock = new Socket(hostName, port); 
			is = new BufferedReader(new InputStreamReader(sock.getInputStream()));			
			os = new PrintWriter(sock.getOutputStream(), true);
		}
		catch(Exception ex) {}
	}
	
	/**
		This method closes the connection between this and the connected server
	*/
	public void close()
	{
		try { sock.close(); }
		catch(Exception ex) {}
	}
	
	/**
		This method sends a string text to the connected server
		@param msg a string text for sending to the connected server
	*/
	public void send(String msg)
	{
		// Do the CRLF ourself since println appends only a \r on
		// platforms where that is the native line ending.
		
		os.print(msg + "\r\n"); 
		os.flush();
		
		DebugInfo.print(DEBUG, "Sent \"" + msg  + "\"");
	}
	
	/** 
		Hold one conversation across the net 
		@param msg a string text for sending to the connected server
		@return receives a list of string texts from the server
	*/
	public List<String> converse(String msg) 
	{
		send(msg);
		return receive();
	}
	
	/**
		This method receives a list of string texts from the connected server
		@return a list of string texts from the connected server
	*/
	public List<String> receive()
	{
		DebugInfo.print(DEBUG, "receive() requested.");
		
		try
		{
			String str = "";
			ArrayList<String> outputs = new ArrayList<String>();

			if((str += is.readLine()) != null || (str += is.readLine()).equals("")) 
			{ 
				outputs.add(str); 
			}
			
			DebugInfo.print(DEBUG, "Got  \"" + str + "\"");
		
			return outputs;
		} 
		
		catch (IOException e) 
		{
			DebugInfo.print(DEBUG, "Client converse() IoException: "+e);
			return null;
		}
	}
}
